﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.SeatPositions.Dtos;
using KDS.Mes.Authorization;
using KDS.Mes.Dto;
using Abp.UI;

namespace KDS.Mes.Mes.SeatPositions
{
    /// <summary>
    /// 座椅位置信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Bom_SeatPositions)]
    public class SeatPositionAppService : MesAppServiceBase, ISeatPositionAppService
    {
        private readonly IRepository<SeatPosition, int> _seatPositionRepository;
        private readonly ISeatPositionListExcelExporter _seatPositionListExcelExporter;


        private readonly SeatPositionManage _seatPositionManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public SeatPositionAppService(IRepository<SeatPosition, int> seatPositionRepository,
SeatPositionManage seatPositionManage
      , ISeatPositionListExcelExporter seatPositionListExcelExporter
  )
        {
            _seatPositionRepository = seatPositionRepository;
            _seatPositionManage = seatPositionManage;
            _seatPositionListExcelExporter = seatPositionListExcelExporter;
        }

        #region 座椅位置信息管理

        public async Task<ListResultDto<SeatPositionListDto>> GetSeatPositions(GetSeatPositionInput input)
        {
            var seatPositions = await _seatPositionRepository.GetAll()
                .ToListAsync();

            return new ListResultDto<SeatPositionListDto>(seatPositions.MapTo<List<SeatPositionListDto>>());
        }

        public PagedResultDto<SeatPositionListDto> GetPagedSeatPositions(GetSeatPositionInput input)
        {
            //初步过滤
            var query = _seatPositionRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<SeatPositionListDto>(tasksCount, taskList.MapTo<List<SeatPositionListDto>>());
        }

        /// <summary>
        /// 根据查询条件获取座椅位置信息分页列表
        /// </summary>
        public async Task<PagedResultDto<SeatPositionListDto>> GetPagedSeatPositionsAsync(GetSeatPositionInput input)
        {

            var query = _seatPositionRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var seatPositionCount = await query.CountAsync();

            var seatPositions = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var seatPositionListDtos = seatPositions.MapTo<List<SeatPositionListDto>>();
            return new PagedResultDto<SeatPositionListDto>(
            seatPositionCount,
            seatPositionListDtos
            );
        }

        /// <summary>
        /// 通过Id获取座椅位置信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetSeatPositionForEditOutput> GetSeatPositionForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetSeatPositionForEditOutput();

            SeatPositionEditDto seatPositionEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _seatPositionRepository.GetAsync(input.Id.Value);
                seatPositionEditDto = entity.MapTo<SeatPositionEditDto>();
            }
            else
            {
                seatPositionEditDto = new SeatPositionEditDto();
            }

            output.SeatPosition = seatPositionEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取座椅位置信息ListDto信息
        /// </summary>
        public async Task<SeatPositionListDto> GetSeatPositionByIdAsync(EntityDto<int> input)
        {
            var entity = await _seatPositionRepository.GetAsync(input.Id);

            return entity.MapTo<SeatPositionListDto>();
        }







        /// <summary>
        /// 新增或更改座椅位置信息
        /// </summary>
        public async Task CreateOrUpdateSeatPositionAsync(CreateOrUpdateSeatPositionInput input)
        {
            if (input.SeatPositionEditDto.Id.HasValue)
            {
                await UpdateSeatPositionAsync(input.SeatPositionEditDto);
            }
            else
            {
                await CreateSeatPositionAsync(input.SeatPositionEditDto);
            }
        }

        /// <summary>
        /// 新增座椅位置信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_SeatPositions_Create)]
        public virtual async Task<SeatPositionEditDto> CreateSeatPositionAsync(SeatPositionEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            
            await CheckSeatPositionIfAlreadyExists(input.SeatPositionName, input.SeatPositionCode, input.Id);
            var entity = input.MapTo<SeatPosition>();

            entity = await _seatPositionRepository.InsertAsync(entity);
            return entity.MapTo<SeatPositionEditDto>();
        }

        /// <summary>
        /// 编辑座椅位置信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_SeatPositions_Edit)]
        public virtual async Task UpdateSeatPositionAsync(SeatPositionEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            await CheckSeatPositionIfAlreadyExists(input.SeatPositionName, input.SeatPositionCode,input.Id);
            var entity = await _seatPositionRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _seatPositionRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除座椅位置信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_SeatPositions_Delete)]
        public async Task DeleteSeatPositionAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _seatPositionRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除座椅位置信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_SeatPositions_Delete)]
        public async Task BatchDeleteSeatPositionAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _seatPositionRepository.DeleteAsync(s => input.Contains(s.Id));
        }


        private async Task CheckSeatPositionIfAlreadyExists(string seatPositionName, string seatPositionCode,int? id=null)
        {
            var existingSeatPosition = await _seatPositionRepository.GetAll()
                .FirstOrDefaultAsync(l => l.SeatPositionName == seatPositionName || l.SeatPositionCode == seatPositionCode);
            if (existingSeatPosition == null)
            {
                return;
            }

            if (id != null && existingSeatPosition.Id == id)
            {
                return;
            }

            throw new UserFriendlyException(L("ThisSeatPositionAlreadyExists"));
            
        }
        #endregion


        #region 座椅位置信息的Excel导出功能


        public async Task<FileDto> GetSeatPositionToExcel()
        {
            var entities = await _seatPositionRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<SeatPositionListDto>>();

            var fileDto = _seatPositionListExcelExporter.ExportSeatPositionToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
